package dataProces;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import javax.swing.JOptionPane;

public class FileOpera {
    private String path;
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date(System.currentTimeMillis());
    FileOutputStream fos=null;
    File file=null;
    OutputStreamWriter osw=null;
    public void exportTxt(LinkedList<String> idioms,String fileName) {
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        path = "data/"+fileName+".txt";
        try {
            file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
                fos = new FileOutputStream(file);
            } else {
                fos = new FileOutputStream(file, true);
            }
            osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            osw.write(formatter.format(date) +(idioms.size()%2==0?"(机器":"(玩家") +"获胜):");
            for (String val: idioms)
                osw.write(val + "——>");
            osw.write('\n');
            osw.close();
            JOptionPane.showMessageDialog(null, "文件已导出至" + path, "提示", JOptionPane.ERROR_MESSAGE);
            logFile("导出账户信息至" + path);
        } catch (IOException e) {
            logFile("账户信息导出:" + e.getMessage());
            JOptionPane.showMessageDialog(null, "文件导出失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }

    }

    public void logFile(String data) {
        formatter = new SimpleDateFormat("yyyy-MM");
        path = "log/IdiomLink-log" + formatter.format(date) + ".txt";
        formatter = new SimpleDateFormat("dd日HH:mm:ss z");
        try {
            file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
                fos = new FileOutputStream(file);
            } else {
                fos = new FileOutputStream(file, true);
            }
            osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            osw.write(formatter.format(date) + ':' + data + "\r\n");
            osw.close();
        } catch (Exception e) {
            System.out.println("日志模块:" + e.getMessage());
        }
    }
}
